package com.manage.system.web.controller;

import com.manage.common.core.dto.token.User;
import com.manage.common.core.result.JsonResult;
import com.manage.common.core.utils.ContextHolderUtils;
import com.manage.common.log.annotation.OperateLog;
import com.manage.common.log.enums.BusinessType;
import com.manage.common.permissions.annotation.HasPermissions;
import com.manage.system.api.constants.ResponseEnum;
import com.manage.system.api.dto.SysUserDto;
import com.manage.system.api.request.user.*;
import com.manage.system.api.response.UserInfoVo;
import com.manage.system.api.service.ISysMenuService;
import com.manage.system.api.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @author zhangqing
 * @version V1.0
 * @description 系统用户控制层
 * @date 6/3/2021 12:49 PM
 */
@RestController
@RequestMapping("/user")
@AllArgsConstructor
@Api(tags = "后台用户管理", value = "SysUserController")
public class SysUserController {

    private final ISysUserService sysUserService;
    private final ISysMenuService sysMenuService;

    @ApiOperation("[Remote->Feign]根据登录名,租户ID。获取用户信息")
    @GetMapping(value = "/loadByUsername")
    public SysUserDto loadByLoginName(@RequestParam String loginName){
        return sysUserService.loadByLoginNameAndTenantCode(loginName);
    }

    @ApiOperation("登录")
    @PostMapping(value = "/login")
    public JsonResult login(@Validated @RequestBody LoginParam loginParam) {
        return sysUserService.login(loginParam.getLoginName(),loginParam.getPassword());
    }

    @ApiOperation("获取当前登录人信息")
    @GetMapping("/info")
    public JsonResult info(){
        User userDto = ContextHolderUtils.getCurrentUser();
        ResponseEnum.UNAUTHORIZED.assertIsEmpty(userDto);
        Long id = userDto.getUserId();
        if(StringUtils.isEmpty(id)){
            ResponseEnum.UNAUTHORIZED.assertFail("token格式不正确");
        }
        UserInfoVo info = sysUserService.info(id);
        Set<String> buttons = sysMenuService.selectPermsByUserId(id);
        info.setButtons(buttons);
        return JsonResult.success(info);
    }

    @ApiOperation("获取所有用户信息")
    @PostMapping("/list")
    @HasPermissions("system:user:list")
    @OperateLog(module = "用户管理",title = "查询用户",businessType = BusinessType.DELETE)
    public JsonResult list(@RequestBody UserQueryParam userParam) {
        return sysUserService.list(userParam);
    }

    @ApiOperation("批量删除用户")
    @DeleteMapping("/batchDel")
    @HasPermissions("system:user:remove")
    @OperateLog(module = "用户管理",title = "批量删除用户",businessType = BusinessType.DELETE)
    public JsonResult batchDel(@RequestBody List<Long> userIds){
        return JsonResult.toJsonResult(sysUserService.delUserByIds(userIds));
    }


    @ApiOperation("更新用户状态")
    @PutMapping("/changeStatus/{id}/{status}")
    @HasPermissions("system:user:edit")
    @OperateLog(module = "用户管理", title = "更新用户状态",businessType = BusinessType.UPDATE)
    public JsonResult changeStatus(@PathVariable("id") Long id,@PathVariable("status") Boolean status){
        return JsonResult.toJsonResult(sysUserService.changeStatus(id,status));
    }

    @ApiOperation("重置用户密码")
    @PutMapping("/resetPassword")
    @HasPermissions("system:user:resetPassword")
    @OperateLog(module = "用户管理",title = "重置用户密码", businessType = BusinessType.OTHER)
    public JsonResult resetPassword(@Validated @RequestBody ResetPasswordParam resetPasswordParam) {
        return JsonResult.toJsonResult(sysUserService.resetPassword(resetPasswordParam));
    }


    @ApiOperation("编辑用户")
    @PutMapping("/edit")
    @HasPermissions("system:user:edit")
    @OperateLog(module = "用户管理",title = "更新用户", businessType = BusinessType.UPDATE)
    public JsonResult edit(@Validated @RequestBody UserUpdateParam userUpdateParam) {
        if (!StringUtils.isEmpty(userUpdateParam.getPhone())) {
            Boolean aBoolean = sysUserService.checkPhoneUnique(userUpdateParam.getPhone(), userUpdateParam.getId());
            ResponseEnum.USER_PHONE_NOT_UNIQUE.assertIsTrue(aBoolean);
        }
        if (!StringUtils.isEmpty(userUpdateParam.getEmail())) {
            Boolean aBoolean = sysUserService.checkEmailUnique(userUpdateParam.getEmail(), userUpdateParam.getId());
            ResponseEnum.USER_EMAIL_NOT_UNIQUE.assertIsTrue(aBoolean);
        }
        return JsonResult.toJsonResult(sysUserService.update(userUpdateParam));
    }

    @ApiOperation("新增用户")
    @PostMapping("/add")
    @HasPermissions("system:user:add")
    @OperateLog(module = "用户管理",title = "新增用户", businessType = BusinessType.INSERT)
    public JsonResult add(@Validated @RequestBody UserAddParam userAddParam) {
        ResponseEnum.USER_LOGIN_NAME_EXISTS.assertIsTrue(sysUserService.checkLoginNameUnique(userAddParam.getPhone()));
        ResponseEnum.USER_PHONE_NOT_UNIQUE.assertIsTrue(sysUserService.checkPhoneUnique(userAddParam.getPhone(), null));
        ResponseEnum.USER_EMAIL_NOT_UNIQUE.assertIsTrue(sysUserService.checkEmailUnique(userAddParam.getEmail(), null));
        return JsonResult.toJsonResult(sysUserService.add(userAddParam));
    }

    @ApiOperation("导出用户")
    @PostMapping("/exportUser")
    @HasPermissions("system:user:export")
    @OperateLog(module = "用户管理",title = "导出用户", businessType = BusinessType.EXPORT)
    public JsonResult exportUser(@RequestBody UserQueryParam userQueryParam) {
        return sysUserService.exportUser(userQueryParam);
    }
}
